<template>
	<div class="status-change-wrap">
		<div class="status-content-top">
			<h3 class="device-subtitle">24小时变化</h3>
			<div class="arrow-wrap" v-if="echartsLength > 1">
				<i class="arrow-left iconfont iconarrow-left" @click="arrowLeft"></i>
				<i class="arrow-right iconfont iconarrow-right" @click="arrowRight"></i>
			</div>
			<!-- 图表 -->
			<div class="echart-waper">
				<div id="historyAnalogChartWaper" class="echart-list" :style="{'left': left+'px'}">
					<div class="status-echarts" v-if="hasAnalog != 1">
						<ul class="barLegend">
							<li>
								<span>报警</span>
							</li>
							<li>
								<span>故障</span>
							</li>
							<li>
								<span>屏蔽</span>
							</li>
							<li>
								<span>联动</span>
							</li>
							<li>
								<span>正常</span>
							</li>
						</ul>
						<div style="width:100%;;height:60%" id="timeBox">
							<div id="timeBar" style="width:610px;height:430px;"></div>
						</div>
					</div>
					<!-- 模拟量图表 -->
				</div>
			</div>
		</div>
		<div class="status-content-bottom">
			<div :class="{ 'is-reset': fireTType===0}" class="porgress-box">
				<div :class="{ 'is-selected':selected===-1,'is-active':handStatusList.indexOf(-1)>-1 }" @click="handleProgressClick(-1)" class="progress-item">发生<br>1</div>
				<div :class="{ 'is-selected':selected===2,'is-active':handStatusList.indexOf(2)>-1 }" @click="handleProgressClick(2)" class="progress-item upward">领取<br>2</div>
				<div :class="{ 'is-selected':selected===1,'is-active':handStatusList.indexOf(1)>-1 }" @click="handleProgressClick(1)" class="progress-item">处理<br>3</div>
				<div :class="{ 'is-selected':selected===0,'is-active':fireTType===0 }" class="progress-item upward is-reset">复位<br>4</div>
			</div>
			<div class="porgress-desc">
				<!-- 正常 -->
				<template v-if="selectedProgress.handStatus===0">
					<div class="status-name-wrap normal-statue">
						<p class="status-name">正常，继续保持</p>
					</div>
				</template>
				<!-- 异常 -->
				<template v-else>
					<div class="status-name-wrap">
						<p class="status-name">{{ statusName }}</p>
					</div>
					<div class="progress-text">
						<p>{{ selectedProgress.happenTime}}</p>
						<p>{{ selectedProgress.desc }}</p>
					</div>
				</template>
			</div>
		</div>
	</div>
</template>
<script>
import utils from '@/utils/util'
import { getFacsHisStatus, getAlarmFcfAnalogInfo } from '@/api/detectorMonitor'
var echarts = require('echarts/lib/echarts')
require('echarts/lib/chart/line')
require('echarts/lib/chart/bar')
require('echarts/lib/component/tooltip')
let statusMap = {
	'-1': '警情发生', // 未处理
	2: '领取任务', // 已领取
	1: '处理任务', // 已处理
}
export default {
	props: {
		deviceInfo: {
			default() {
				return false
			},
		},
	},
	data() {
		return {
			fireTType: '',
			recordsInfoHandlerStatus: '',
			handlerAccountName: '', // 领取人
			recordsInfoHandlerTime: '', // 领取时间
			recordsInfoCreateTime: '', // 发生时间
			noDataFlag: true,
			echartsLength: 0,
			hasAnalog: 1,
			left: 0,
			selected: '',
			handList: [],
			handStatusList: [],
			selectedProgress: {},
		}
	},
	computed: {
		statusName() {
			return statusMap[this.selected] || ''
		},
	},
	created() {},
	methods: {
		handleProgressClick(val) {
			if (this.handStatusList.indexOf(val)<0) return
			this.selected = val
		},
		isProgressActive(status) {
			return (
				this.handList.filter((n) => {
					return n.handStatus === status
				}).length > 0
			)
		},
		// 映射状态处理结果描述
		mapDescStatus() {
			let Map = {
				'-1': '未领取', // 未处理
				2: '领取任务', // 已领取
				1: '处理任务', // 已处理
			}
			return Map[this.recordsInfoHandlerStatus]
		},
		arrowLeft() {
			if (this.left < 0) {
				this.left += 610
			}
		},
		arrowRight() {
			if (this.left > -610 * (this.echartsLength - 1)) {
				this.left -= 610
			}
		},
		// 获取24小时内状态变化
		getStatusFor24Hours() {
			let that = this
			getFacsHisStatus({
				fcfId: that.deviceInfo.fcfId,
				type: 1,
			}).then((res) => {
				if (res.status === 200) {
					that.echartsLength += 1
					that.getBar(res.data)
				}
			})
		},
		// 获取模拟量信息
		getDeviceAnalogData() {
			let that = this
			let yDataValue = []
			let yData = []
			let yMax = null
			let fcfId = that.deviceInfo.fcfId
			let startTime = utils.ilinkTimeformat.hoursAgo(24, 'yyyy-MM-dd hh:mm:ss')
			getAlarmFcfAnalogInfo({
				startTime: startTime, //	开始时间（yyyy-MM-dd HH:MM:SS)
				fcfId: fcfId, // 消防设施编码
				num: 100,
			}).then((res) => {
				if (res.status === 200) {
					let data = res.data
					if (data && data.length > 0) {
						that.noDataFlag = true
						//处理模拟量类型数据  设备电压不画
						if (data.length == 1 && data[0].dataTypeId == 3) {
							// 不显示
							that.noDataFlag = true
							return false
						}
						for (var i = 0; i < data.length; i++) {
							yDataValue = []
							yData = []
							if (data[i].dataTypeId != 3) {
								if (data[i].detail && data[i].detail.length > 0) {
									that.noDataFlag = false
									let dataTime = data[i].detail
									for (var n = 0; n < dataTime.length; n++) {
										yDataValue.push(dataTime[n].analogValue)
										yData.push({
											name: dataTime[n].datetime,
											value: [
												utils.ilinkTimeformat.format(
													new Date(dataTime[n].datetime),
													'yyyy-MM-dd hh:mm'
												),
												dataTime[n].analogValue,
											],
										})
									}
									$('#historyAnalogChartWaper').append(
										`<div class="every-type-chart-wrap" id="every-historyChart-` +
											data[i].dataTypeId +
											`" style="padding:20px 0">
                      <p class="chat-title" id="historyChart-bar-title" style="color: #A3BEDD;">` +
											data[i].dataTypeName +
											`变化（` +
											data[i].detail[0].analogUnits +
											`）</p>
                      <div class="content-analog-chart" id="historyChart-bar-` +
											fcfId +
											'_' +
											data[i].dataTypeId +
											`" style="width:610px;;height:380px;"></div>
                    </div>`
									)
									//y轴最大值
									yMax = Math.max(...yDataValue)
									yMax = Math.max(yMax, data[i].thresholdMax ? data[i].thresholdMax : 0)
									that.echartsLength += 1
									that.drawEqChartEqmentMsg(
										yDataValue,
										yData,
										yMax,
										data[i].thresholdMin ? data[i].thresholdMin : 0,
										data[i].thresholdMax ? data[i].thresholdMax : 0,
										data[i].dataTypeName,
										'historyChart-bar-' + fcfId + '_' + data[i].dataTypeId,
										data[i].detail[0].analogUnits
									)
								}
							}
						}
					} else {
						// 暂无数据
						that.noDataFlag = true
					}
					this.loading = false
				}
			})
		},
		//画折线图
		drawEqChartEqmentMsg(
			yDataValue,
			yAxisData,
			yMax,
			thresholdMin,
			thresholdMax,
			title,
			domId,
			analogUnits
		) {
			var self = this
			var markLineArr = []

			if (thresholdMin) {
				markLineArr.push({
					name: '下阈值',
					yAxis: thresholdMin,
				})
			}
			if (thresholdMax) {
				markLineArr.push({
					name: '上阈值',
					yAxis: thresholdMax,
				})
			}

			let option = {
				title: {
					text: '',
				},
				grid: {
					top: '10%',
					left: '30px',
					right: '30px',
					bottom: '0',
					containLabel: true,
				},
				tooltip: {
					position: function (p) {
						//其中p为当前鼠标的位置
						return [p[0] - 28, p[1] - 70]
					},
					padding: 5,
					trigger: 'axis',
					formatter: function (e) {
						var data = e[0]
						return (
							`<span style='font-size:12px;'>` +
							data.value[0] +
							`</span><br/><span style='font-size:14px;'>` +
							data.value[1] +
							analogUnits +
							`</span>`
						)
					},
					textStyle: { align: 'center' },
					confine: true,
				},
				xAxis: [
					{
						type: 'time',
						boundaryGap: false,
						axisLine: {
							lineStyle: {
								color: 'rgba(225, 225, 225, 0.3)',
							},
						},
						axisLabel: {
							show: true,
							textStyle: {
								color: '#666',
							},
							formatter: function (params) {
								return utils.ilinkTimeformat.format(new Date(params), 'hh:mm')
							},
						},
						splitLine: {
							show: false,
							lineStyle: {
								color: '#f4f7f9',
							},
						},
					},
				],
				yAxis: [
					{
						type: 'value',
						max: yMax,
						splitNumber: 0.5,
						axisLine: {
							lineStyle: {
								color: 'rgba(225, 225, 225, 0.3)',
							},
						},
						axisLabel: {
							show: true,
							textStyle: {
								color: '#666',
							},
							formatter: function (params) {
								return String(params) + analogUnits
							},
						},
						splitLine: {
							show: false,
							lineStyle: {
								color: '#f4f7f9',
							},
						},
					},
				],
				series: [
					{
						type: 'line',
						areaStyle: {
							normal: {
								color: '#112b48',
								// color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								//   { offset: 0, color: "rgba(57, 126, 206, 0.6)" },
								//   { offset: 0.5, color: "rgba(57, 126, 206, 0.4)" },
								//   { offset: 1, color: "#fff" }
								// ])
							},
						},
						smooth: true,
						showSymbol: false, //不展示节点
						itemStyle: {
							normal: {
								color: 'rgba(55, 139, 246, 0.8)', // 会设置点和线的颜色，所以需要下面定制
								borderColor: 'rgba(55, 139, 246, 0.8)', // 点边线的颜色
							},
						},
						lineStyle: {
							normal: {
								color: 'rgba(55, 139, 246,0.9)', // 线条颜色
							},
						},
						markLine: {
							itemStyle: {
								normal: {
									lineStyle: {
										type: 'dashed',
										color: 'red',
									},
									label: {
										show: true,
										position: 'middle', //'start' 线的起始点。'middle' 线的中点。'end' 线的结束点。
										formatter: function (param) {
											return param.name + param.value
										},
										textStyle: {
											fontSize: 16,
										},
									},
								},
							},
							//symbolSize:0,
							silent: true,
							data: markLineArr,
						},
						data: yAxisData,
					},
				],
			}
			this.$nextTick(() => {
				if (document.getElementById(domId)) {
					echarts.init(document.getElementById(domId)).setOption(option)
				}
			})
		},
		getBar(listData) {
			this.$nextTick(() => {
				//处理强制刷新 动态 渲染echarts dom
				// document.getElementById(
				//   "timeBar"
				// ).style.width = window.getComputedStyle(
				//   document.getElementById("timeBox")
				// ).width;
				// document.getElementById(
				//   "timeBar"
				// ).style.height = window.getComputedStyle(
				//   document.getElementById("timeBox")
				// ).height;
				let data = listData
				let dataY = data.map((item, index, arr) => {
					let value = String(item.date).substring(8) + ':00'
					return value
				})
				var arr = data.map((item, index, arr) => {
					let value = item.fireTType
					// 将状态转换成分值
					if (value == 0 || !value) {
						value = 5
					} else if (value == 10) {
						value = 25
					} else if (value == 20) {
						value = 20
					} else if (value == 30) {
						value = 15
					} else if (value == 40) {
						value = 10
					} else {
						value = 5
					}
					return { value: value, fireTType: item.fireTType }
				})
				let option = {
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow',
						},
						formatter: function (e) {
							let value = e[0].value
							switch (value) {
								case 0:
									return e[0].name + ' 设备正常'
									break
								case 10:
									return e[0].name + ' 设备报警'
									break
								case 20:
									return e[0].name + ' 设备故障'
									break
								case 30:
									return e[0].name + ' 设备屏蔽'
									break
								case 40:
									return e[0].name + ' 设备联动'
									break
							}
						},
					},

					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						containLabel: true,
					},
					xAxis: {
						type: 'value',
						interval: 5,
						max: 25,
						axisLabel: {
							color: '#FFFFFF',
						},
						splitLine: {
							//网格线
							show: false,
						},
						axisLabel: {
							show: true,
							textStyle: {
								color: '#666',
							},
							formatter: function (value) {
								if (value == 5) {
									return '正常'
								} else if (value == 10) {
									return '联动'
								} else if (value == 15) {
									return '屏蔽'
								} else if (value == 20) {
									return '故障'
								} else if (value == 25) {
									return '报警'
								} else {
									return ''
								}
							},
						},
					},
					yAxis: {
						type: 'category',
						data: dataY,
						axisLabel: {
							color: '#FFFFFF',
						},
					},
					series: [
						{
							name: '状态:',
							type: 'bar',
							data: arr,
							itemStyle: {
								//通常情况下：
								normal: {
									color: function (params) {
										var status = params.data.fireTType
										for (var i = 0; i < arr.length; i++) {
											switch (status) {
												case 0: //正常
													return new echarts.graphic.LinearGradient(1, 0, 0, 0, [
														{ offset: 0, color: 'rgba(119, 190, 7, 1)' },
														{
															offset: 0.002,
															color: 'rgba(119, 190, 7, 0.95)',
														},
														{
															offset: 0.03,
															color: 'rgba(119, 190, 7, 0.15)',
														},
														{ offset: 0.7, color: 'rgba(119, 190, 7, 0.1)' },
														{ offset: 0.9, color: 'rgba(119, 190, 7, 0.05)' },
														{ offset: 1, color: 'rgba(119, 190, 7, 0.05)' },
													])
													break
												case 10: //报警
													return new echarts.graphic.LinearGradient(1, 0, 0, 0, [
														{ offset: 0, color: 'rgba(254, 102, 104, 1)' },
														{
															offset: 0.002,
															color: 'rgba(254, 102, 104, 0.95)',
														},
														{
															offset: 0.03,
															color: 'rgba(254, 102, 104, 0.15)',
														},
														{
															offset: 0.7,
															color: 'rgba(254, 102, 104, 0.1)',
														},
														{
															offset: 0.9,
															color: 'rgba(254, 102, 104, 0.05)',
														},
														{ offset: 1, color: 'rgba(254, 102, 104, 0.05)' },
													])
													break
												case 20: //故障
													return new echarts.graphic.LinearGradient(1, 0, 0, 0, [
														{ offset: 0, color: 'rgba(248, 183, 40, 1)' },
														{
															offset: 0.002,
															color: 'rgba(248, 183, 40, 0.95)',
														},
														{
															offset: 0.03,
															color: 'rgba(248, 183, 40, 0.15)',
														},
														{ offset: 0.7, color: 'rgba(248, 183, 40, 0.1)' },
														{
															offset: 0.9,
															color: 'rgba(248, 183, 40, 0.05)',
														},
														{ offset: 1, color: 'rgba(248, 183, 40, 0.05)' },
													])
													break
												case 30: //屏蔽
													return new echarts.graphic.LinearGradient(1, 0, 0, 0, [
														{ offset: 0, color: 'rgba(153, 153, 153, 1)' },
														{
															offset: 0.002,
															color: 'rgba(153, 153, 153, 0.95)',
														},
														{
															offset: 0.03,
															color: 'rgba(153, 153, 153, 0.15)',
														},
														{
															offset: 0.7,
															color: 'rgba(153, 153, 153, 0.1)',
														},
														{
															offset: 0.9,
															color: 'rgba(153, 153, 153, 0.05)',
														},
														{ offset: 1, color: 'rgba(153, 153, 153, 0.05)' },
													])
													break
												case 40: //联动
													return new echarts.graphic.LinearGradient(1, 0, 0, 0, [
														{ offset: 0, color: 'rgba(55, 139, 246, 1)' },
														{
															offset: 0.002,
															color: 'rgba(55, 139, 246, 0.95)',
														},
														{
															offset: 0.03,
															color: 'rgba(55, 139, 246, 0.15)',
														},
														{ offset: 0.7, color: 'rgba(55, 139, 246, 0.1)' },
														{
															offset: 0.9,
															color: 'rgba(55, 139, 246, 0.05)',
														},
														{ offset: 1, color: 'rgba(55, 139, 246, 0.05)' },
													])
													break
											}
										}
									},
								},
								//鼠标悬停时：
								emphasis: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)',
								},
							},
						},
					],
				}
				if (document.getElementById('timeBar')) {
					echarts.init(document.getElementById('timeBar')).setOption(option)
				}
			})
		},
		getProgressByStatus(val) {
			if (val === 0) {
				this.selectedProgress = {
					handStatus: 0,
					desc: '正常，继续保持',
					happenTime: this.recordsInfoHandlerTime,
				}
			} else {
				let obj =
					this.handList.filter((n) => {
						return n.handStatus == val
					})[0] || {}
				this.selectedProgress = Object.assign({}, obj)
			}
		},
	},
	watch: {
		selected(val) {
			if(val!==''){
				this.getProgressByStatus(val)
			}
		},
		deviceInfo(val, oldVal) {
			this.selected=''
			let that = this
			if (val) {
				that.left = 0
				// 删除上一次动态添加的模拟量图表
				$('#historyAnalogChartWaper .every-type-chart-wrap').remove()
				that.echartsLength = 0 // 重置统计图表个数
				that.detailsInfo = val
				that.fireTType = val.fireTType // 设备状态
				that.hasAnalog = val.hasAnalog // 有无模拟量
				that.recordsInfoHandlerStatus = val.recordsInfoHandlerStatus
				that.handlerAccountName = val.handlerAccountName
				that.recordsInfoHandlerTime = val.recordsInfoHandlerTime
				that.recordsInfoCreateTime = val.recordsInfoCreateTime

				this.handList = val.handList || [
					// {
					// 	handStatus: -1,
					// 	desc: '警情发生',
					// 	happenTime: '2020-10-12 15:23:14',
					// },
					// {
					// 	handStatus: 2,
					// 	desc: '警情领取',
					// 	happenTime: '2020-10-12 15:23:14',
					// },
					// {
					// 	handStatus: 1,
					// 	desc: '警情处理',
					// 	happenTime: '2020-10-12 15:23:14',
					// },
				]
				this.handStatusList = this.handList.map((n) => {
					return n.handStatus
				})
				this.$nextTick(()=>{
					this.selected = this.fireTType === 0 ? 0 : this.recordsInfoHandlerStatus
				})

				// 判断有模拟量渲染模拟量图表
				if (val.hasAnalog == 1) {
					that.getDeviceAnalogData()
				} else if (val.hasAnalog == 2) {
					that.getStatusFor24Hours()
					that.getDeviceAnalogData()
				} else {
					that.getStatusFor24Hours()
				}
				that.$Ctl.loading(0)
			}
		},
	},
}
</script>
<style lang="scss" scope>
.status-change-wrap {
	margin-left: 40px;
	padding-top: 20px;
	.status-content-top {
		height: calc(55% - 10px);
		position: relative;
		.device-subtitle {
			margin-left: 10px;
			width: 260px;
			height: 26px;
			line-height: 26px;
			font-size: 20px;
			color: #55abf3;
			font-weight: bold;
			background: url('../../../../../assets/images/detailPage/icon-info.png') no-repeat;
			background-size: 100% 100%;
			text-align: center;
			letter-spacing: 3px;
		}
		.arrow-wrap {
			position: absolute;
			top: -5px;
			right: 80px;
			.arrow-right,
			.arrow-left {
				font-size: 36px;
				color: #4d5c6b;
				cursor: pointer;
				&:hover {
					color: #1da1f5;
				}
			}
		}
		.echart-waper {
			position: relative;
			width: 100%;
			height: 430px;
			overflow: hidden;
			.echart-list {
				position: absolute;
				display: flex;
				top: 0;
				left: 0;
				height: 430px;
			}
		}
		.status-echarts {
			position: relative;
			.barLegend {
				display: flex;
				align-items: center;
				justify-content: flex-start;
				position: absolute;
				top: 15px;
				right: 0;
				li {
					position: relative;
					padding-left: 10px;
					margin-right: 20px;
					&:nth-child(1) {
						&::before {
							content: '';
							width: 6px;
							height: 6px;
							background: #ce334f;
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
						}
					}
					&:nth-child(2) {
						&::before {
							content: '';
							width: 6px;
							height: 6px;
							background: #f0a045;
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
						}
					}
					&:nth-child(3) {
						&::before {
							content: '';
							width: 6px;
							height: 6px;
							background: #dadada;
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
						}
					}
					&:nth-child(4) {
						&::before {
							content: '';
							width: 6px;
							height: 6px;
							background: #2a78ed;
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
						}
					}
					&:nth-child(5) {
						&::before {
							content: '';
							width: 6px;
							height: 6px;
							background: #67b692;
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
						}
					}
				}
			}
		}
	}
	.status-content-bottom {
		height: calc(45% + 10px);
		.porgress-box {
			margin-top: 70px;
			position: relative;
			&.is-reset {
				.progress-item {
					cursor: default;
				}
			}
			.progress-item {
				position: relative;
				display: inline-block;
				padding-top: 60px;
				width: 152px;
				height: 152px;
				background: url(../../../../../assets/images/detailPage/progress-bg.png) center no-repeat;
				background-size: 100% 100%;
				font-size: 20px;
				text-align: center;
				&.is-active {
					background-image: url(../../../../../assets/images/detailPage/selectProgress.png);
					cursor: pointer;
				}
				&.is-selected {
					animation: 2s pulsate linear infinite normal;
				}
				&.is-reset {
					cursor: default;
				}
			}
			.upward {
				top: -50px;
			}
		}
		.porgress-desc {
			height: 33.33%;
			margin-top: 20px;
			display: flex;
			align-items: center;
			justify-content: flex-start;
			background: rgba(81, 166, 250, 0.1);
			border-radius: 4px;
			.status-name-wrap {
				background: url('../../../../../assets/images/detailPage/icon-bottom.png') no-repeat;
				width: 160px;
				height: 80px;
				line-height: 80px;
				text-align: center;
				background-size: 100% 100%;
				font-size: 18px;
				color: #4699ff;
				margin: 0 20px;
				&.normal-statue {
					margin: 0 auto;
					width: 380px;
				}
				.status-name {
					font-size: 28px;
					font-weight: bold;
					color: rgba(85, 171, 243, 1);
					background: linear-gradient(0deg, rgba(99, 189, 241, 1) 0%, rgba(70, 153, 255, 1) 100%);
					-webkit-background-clip: text;
					-webkit-text-fill-color: transparent;
				}
			}
      .progress-text{
				padding-right: 10px;
        flex:1;
      }
			div {
				&:nth-child(2) {
					font-size: 18px;
					p {
						color: #ffffff;
						line-height: 30px;
						&:nth-child(1) {
							color: #a3bedd;
							font-size: 18px;
							line-height: 30px;
						}
					}
				}
			}
		}
	}
	@keyframes pulsate {
		0% {
			transform: translateY(0px);
		}
		50% {
			transform: translateY(-20px);
		}
		100% {
			transform: translateY(0px);
		}
	}
}
</style>
